/* eslint-disable react/no-direct-mutation-state */
import React, { Component } from 'react'
import './css/app.css'

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      message: [
        { id: 1, name: '铅球', cout: 5, price: 99 },
        { id: 2, name: '棒球', cout: 2, price: 59 },
        { id: 3, name: '篮球', cout: 3, price: 69 },
        { id: 4, name: '羽毛球', cout: 2, price: 82 },
      ]
    }

    

    localStorage.setItem('message', JSON.stringify(this.state.message))
  }

  sum = () => {
    // 0 表示转换为数值型
    var total = this.state.message.reduce((v, t) => v + t.price * t.cout, 0)
    localStorage.setItem('message', JSON.stringify(this.state.message))
    console.log(total)
    return total

  }


  minus = (index) => {
    this.state.message[index].cout -= 1
    this.setState({ message: this.state.message })
    localStorage.setItem('message', JSON.stringify(this.state.message))
  }

  add = (index) => {
    const lgs= localStorage.getItem('message')
    if(lgs){
      this.state.message[index].cout += 1
      this.setState({ message: this.state.message })
    }
    localStorage.setItem('message', JSON.stringify(this.state.message))
  }

  render() {
    return (
      <div>
        <table>
          <thead>
            <th>商品名称</th>
            <th>数量</th>
            <th>单价</th>
            <th>价格</th>
          </thead>
          <tbody>
            {
              this.state.message.map((item, index) => (
                <tr key={item.id}>
                  <td>{item.name}</td>
                  <td> <button disabled={item.cout <= 1} onClick={() => this.minus(index, -1)}>-</button> {item.cout} <button disabled={item.cout >= 10} onClick={() => this.add(index, +1)}>+</button></td>
                  <td>{item.price}</td>
                  <td>{item.cout * item.price}</td>
                </tr>
              ))
            }
          </tbody>
          <p>合计:{this.sum()}</p><span>{this.sum.total}</span>
        </table>
      </div>
    )
  }
}
